package com.chinapost.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chinapost.dao.BaseDaoI;
import com.chinapost.po.Tdqobk;
import com.chinapost.service.DqobkServiceI;
import com.chinapost.vo.DataGrid;
import com.chinapost.vo.Dqobk;

@Service("dqobkService")
public class DqobkServiceImpl implements DqobkServiceI {

	@Autowired
	private BaseDaoI<Tdqobk> dqobkDao;


	@Override
	public DataGrid datagrid(Dqobk dqobk) {
		DataGrid dg = new DataGrid();
		dg.setRows(listRows(find(dqobk)));
		dg.setTotal(total(dqobk));
		return dg;
	}

	private Long total(Dqobk dqobk) {
		String hql = "select count(*) from Tdqobk t where 1=1";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(dqobk, hql, params);
		return dqobkDao.count(hql, params);
	}

	private List<Tdqobk> find(Dqobk dqobk) {
		String hql = "from Tdqobk t where 1=1";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(dqobk, hql, params);
		if (dqobk.getOrder() != null && dqobk.getSort() != null) {
			hql += " order by " + dqobk.getSort() + " " + dqobk.getOrder();
		}
		return dqobkDao.find(hql, params, dqobk.getPage(), dqobk.getRows());
	}

	private List<Dqobk> listRows(List<Tdqobk> lt) {
		List<Dqobk> rows = new ArrayList<Dqobk>();
		if (lt != null && lt.size() > 0) {
			for (Tdqobk t : lt) {
				Dqobk sub = new Dqobk();
				BeanUtils.copyProperties(t, sub);
				rows.add(sub);
			}
		}
		return rows;
	}

	private String addWhere(Dqobk dqobk, String hql, Map<String, Object> params) {
		if (dqobk != null && dqobk.getCybt() != null && !dqobk.getCybt().trim().equals("")) {
			hql += " and t.cybt like :ybt ";
			params.put("ybt", "%%" + dqobk.getCybt() + "%%");
		}
		return hql;
	}

	

}
